package tablet.module_user.activity;

import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.lib.app.ARouterPathUtils;
import com.lib.app.CodeUtil;
import com.lib.bean.UpdateVersionBean;
import com.lib.fastkit.db.shared_prefrences.SharedPreferenceManager;
import com.lib.fastkit.http.ok.HttpUtils;
import com.lib.fastkit.utils.clear_cache.ClearDataUtils;
import com.lib.fastkit.utils.log.LogUtil;
import com.lib.fastkit.utils.system.SystemUtil;
import com.lib.fastkit.views.dialog.http.DialogUtils;
import com.lib.fastkit.views.dialog.normal.CoachAIStudyDialog;
import com.lib.http.call_back.HttpNormalCallBack;
import com.lib.ui.activity.BaseAppActivity;
import com.lib.utls.appupdate.AppDownloadManager;
import com.lib.view.navigationbar.NomalNavigationBar;

import butterknife.BindView;
import butterknife.OnClick;
import tablet.module_user.R;
import tablet.module_user.R2;

import static java.util.ResourceBundle.clearCache;

@Route(path = ARouterPathUtils.Tablet_User_SetActivity)
public class SetActivity extends BaseAppActivity {

    @BindView(R2.id.lin_clear)
    LinearLayout linClear;
    @BindView(R2.id.lin_update)
    LinearLayout linUpdate;
    @BindView(R2.id.lin_help)
    LinearLayout linHelp;
    @BindView(R2.id.lin_about)
    LinearLayout linAbout;
    @BindView(R2.id.tv_cache)
    TextView tvCache;
    @BindView(R2.id.tv_update)
    TextView tvUpdate;

    @BindView(R2.id.lin_cancelaccount)
    LinearLayout linCancelaccount;

    AppDownloadManager downloadManager;


    @Override
    protected void onCreateView() {

        initTitle();

        initView();

    }

    private DialogUtils dialogUtils;

    private void initView() {

        setCache();
        String version = SystemUtil.getVerName(this);
        tvUpdate.setText(version);
        dialogUtils = new DialogUtils();

    }

    private void setCache() {
        try {
            String cacheSize = ClearDataUtils.getTotalCacheSize(this);
            tvCache.setText(cacheSize);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void initTitle() {
        NomalNavigationBar navigationBar = new
                NomalNavigationBar.Builder(this)
                .setTitle("设置")
                .setRightClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        showToast("点击分享");
                    }
                })
                .builder();


    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_set;
    }


    @OnClick({R2.id.lin_clear, R2.id.lin_update, R2.id.lin_help, R2.id.lin_about, R2.id.lin_cancelaccount})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.lin_clear) {

//            CoachAIStudyDialog.getInstance()
//                    .setTitle("温馨提示")
//                    .setContent("")
//                    .setSureListener(new CoachAIStudyDialog.SurelListener() {
//                        @Override
//                        public void onSure() {
//
//                        }
//                    })
//                    .setCancelListener(new CoachAIStudyDialog.CancelListener() {
//                        @Override
//                        public void onCancel() {
//
//
//                        }
//                    }).show(getSupportFragmentManager());

            clearTabletCache();


        } else if (i == R.id.lin_update) {

            showUpdateDialog();

        } else if (i == R.id.lin_help) {
            ARouter.getInstance().build(ARouterPathUtils.User_HelpActivity).navigation();

        } else if (i == R.id.lin_about) {

            ARouter.getInstance().build(ARouterPathUtils.App_AboutActivity).navigation();
        }
    }

    private void clearTabletCache() {

        CoachAIStudyDialog.getInstance()
                .setTitle("清理缓存")
                .setContent("你确认要缓存么?")
                .setCancelListener(new CoachAIStudyDialog.CancelListener() {
                    @Override
                    public void onCancel() {

                    }
                })
                .setSureListener(new CoachAIStudyDialog.SurelListener() {

                    @Override
                    public void onSure() {
                        dialogUtils.showNormalDialog(SetActivity.this, "缓存清理中...");

                        ClearDataUtils.clearAllCache(SetActivity.this);
                        ClearDataUtils.cleanWebViewCache(SetActivity.this);

                        /**
                         * 清除 token
                         */
//                        SharedPreferenceManager.getInstance(SetActivity.this).getUserCache().setUserToken("");

                        /**
                         * 清除等待状态
                         */
                        SharedPreferenceManager.getInstance(SetActivity.this).getUserCache().setIsWait(0);

                        /**
                         * 清除图片缓存
                         * 该方法必须在主线程
                         */
                        Glide.get(SetActivity.this).clearMemory();
                        new Thread(new Runnable() {
                            @Override
                            public void run() {

                                /**
                                 * 清除图片缓存
                                 * 该方法必须在子线程
                                 */
                                Glide.get(SetActivity.this).clearDiskCache();

                            }
                        }).start();

                        setCache();
                        dialogUtils.dismiss();

                        //清理缓存之后，需要重新登录
//                        ARouter.getInstance().build(ARouterPathUtils.User_LoginActivity).navigation();

                    }


                })
                .show(getSupportFragmentManager());

    }

    private void cancelAccount() {


    }


    @Override
    protected void onResume() {
        super.onResume();

        if (downloadManager != null) {
            downloadManager.resume();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();

        if (downloadManager != null) {
            downloadManager.onPause();
        }
    }

    private void showUpdateDialog() {

//        HttpUtils.with(this)
//                .addParam("requestType", "VERSION")
//                .addParam("version_type", "0")
//                .execute(new HttpNormalCallBack<UpdateVersionBean>() {
//                    @Override
//                    public void onSuccess(UpdateVersionBean result) {
//
//                        if (CodeUtil.CODE_200 == result.getCode()) {
//
//                            double localVersion = SystemUtil.getVersionCode(SetActivity.this);
//                            double newVersion = 0;
//                            if (!"".equals(result.getObj().getVersion()) || null != result.getObj().getVersion()) {
//                                newVersion = Double.parseDouble(result.getObj().getVersion());
//                            }
//                            if (newVersion > localVersion) {
//                                showRemindDialog(result);
//                            } else {
//                                showToast("当前已是最新版本");
//                            }
//                        }
//                    }
//
//                    @Override
//                    public void onError(String e) {
//
//                    }
//                });

        HttpUtils.with(this)
                .addParam("requestType", "TABLET_VERSION")
                .addParam("version_type", "2")
                .addParam("token", SharedPreferenceManager.getInstance(this).getUserCache().getUserToken())
                .execute(new HttpNormalCallBack<UpdateVersionBean>() {
                    @Override
                    public void onSuccess(UpdateVersionBean result) {

                        if (CodeUtil.CODE_200 == result.getCode()) {

                            double localVersion = SystemUtil.getVersionCode(SetActivity.this);

                            double newVersion = 0;

                            if (!"".equals(result.getObj().getVersion()) || null != result.getObj().getVersion()) {
                                newVersion = Double.parseDouble(result.getObj().getVersion());
                            }

                            if (newVersion > localVersion) {
                                showRemindDialog(result);
                            } else {
                                showToast("当前已是最新版本！");
                            }
                        }
                    }

                    @Override
                    public void onError(String e) {

                    }
                });

    }

    private void showRemindDialog(final UpdateVersionBean result) {

        downloadManager = new AppDownloadManager(SetActivity.this);

        if (downloadManager != null) {
            downloadManager.resume();
        }

        CoachAIStudyDialog.getInstance()
                .setTitle("温馨提示")
                .setContent("已检测到学思兔新版本" + result.getObj().getVersion_name() + "，快去更新吧！")
                .setCancelListener(new CoachAIStudyDialog.CancelListener() {
                    @Override
                    public void onCancel() {

                    }

                })
                .setSureListener(new CoachAIStudyDialog.SurelListener() {
                    @Override
                    public void onSure() {

                        String title = "版本-" + result.getObj().getVersion_name();
                        String desc = "新版来啦";
                        showToast("学思兔-" + result.getObj().getVersion_name() + "-正在下载中...");
                        downloadManager.setUpdateListener(new AppDownloadManager.OnUpdateListener() {
                            @Override
                            public void update(int currentByte, int totalByte) {
                                LogUtil.e("------------------------当前的大小为：" + currentByte);
                                LogUtil.e("------------------------总的大小为：" + totalByte);

                            }
                        });
                        downloadManager.downloadApk(result.getObj().getDownload_url(), title, desc);

                    }


                })
                .show(getSupportFragmentManager());


    }


}
